package com.dbutil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.entity.Product;

import net.coobird.thumbnailator.Thumbnails;

public class Upload {
	
	/**
	 * 得到本地上传路径
	 * @param request   HttpServletRequest  请求
	 * @param itemnext  上传项项目下文件路径
	 * @return String url
	 */
	public static String geturl(HttpServletRequest request,String itemnext) {
		String t = request.getSession().getServletContext().getRealPath(itemnext);
		String url = t.substring(0,t.indexOf("."))+itemnext;
		return url;
	}
	
	/**
	 * 图片上传
	 * @param request   HttpServletRequest 请求
	 * @param url   上传地址
	 * @return  图片名称
	 */
	public static Product imagesupload(HttpServletRequest request,String url) {
		
		DiskFileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload upload=new ServletFileUpload(factory);
		Product pr = new Product();
		
		//利用文件
		try {
			List<FileItem> list=upload.parseRequest(request);
			for(FileItem fi:list){
				//如果是普通
				if(fi.isFormField()){
					
					String name = fi.getFieldName();
					String value = fi.getString("UTF-8");
					//System.out.println(name+":"+value);
					switch(name) {
					case "id":pr.setEP_ID(Integer.parseInt(value));break;
					case "productName":pr.setEP_NAME(value);break;
					case "photo2":pr.setEP_FILE_NAME(value);break;
					case "productms":pr.setEP_DESCRIPTION(value);break;
					case "parentId":pr.setEPC_CHILD_ID(Integer.parseInt(value));break;
					case "productPrice":pr.setEP_PRICE(new Float(value));break;
					case "kc":pr.setEP_STOCK(Integer.parseInt(value));break;
					}
				}else{
					if(fi.getName().endsWith(".jpg") || fi.getName().endsWith(".png")) {
						
						long ti=new Date().getTime();
						int wz=fi.getName().lastIndexOf(".");
						String pricn=fi.getName().substring(wz+1);
						//System.out.println("后缀名："+pricn);
						String pna=ti+"."+pricn;
						pr.setEP_FILE_NAME(pna);
						//System.out.println("图片名："+pna);
						InputStream in=fi.getInputStream();
						//路径
						File f=new File(url+"/"+pna);
						Long size=fi.getSize();
						//判断大小
						if(size>204800) {
							//图片进行压缩
							Thumbnails.of(fi.getInputStream()).scale(1f).outputQuality(0.25f).toFile(f);
						}else {
							FileOutputStream out=new FileOutputStream(f);
							byte[] b= new byte[1024];
							int len;
							while((len=in.read(b))>-1){
								out.write(b,0,len);
							}
							out.close();
							in.close();
						}
					}else {
						System.out.println("文件传入错误！");
					}
				}
			}
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return pr;
	}
	
}
